/**
 * Copyright (C) 2013-2014 EaseMob Technologies. All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *     http://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.hengtiansoft.lfy.chart.activity;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.NetworkResponse;
import com.android.volley.Request.Method;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.HttpHeaderParser;
import com.hengtiansoft.lfy.base.BaseActivity;
import com.hengtiansoft.lfy.chart.applib.controller.HXSDKHelper;
import com.hengtiansoft.lfy.chart.applib.utils.HXPreferenceUtils;
import com.google.gson.reflect.TypeToken;
import com.hengtiansoft.lfy.chart.DemoHXSDKHelper;
import com.hengtiansoft.lfy.LFYApplication;
import com.hengtiansoft.lfy.R;
import com.hengtiansoft.lfy.chart.action.SearchFriendsJson;
import com.hengtiansoft.lfy.chart.adapter.SearchFriendsAdapter;
import com.hengtiansoft.lfy.chart.adapter.SearchFriendsAdapter.SearchFriendsAdapterListener;
import com.hengtiansoft.lfy.chart.bean.BaseResult;
import com.hengtiansoft.lfy.chart.bean.UserVO;
import com.hengtiansoft.lfy.constants.Constants;
import com.hengtiansoft.lfy.utils.Config;
import com.hengtiansoft.lfy.widget.AlertDialog;
import com.hengtiansoft.lfy.chart.net.JsonListRequest;
import com.hengtiansoft.lfy.chart.net.VolleyUtil;
import com.hyphenate.chat.EMClient;

import java.io.UnsupportedEncodingException;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class AddContactSearchActivity extends BaseActivity {
    private static String TAG = "AddContactActivity";
    private EditText editText;
    private LinearLayout searchedUserLayout;
    private TextView nameText, mTextView;
    private Button searchBtn;
    private ImageView avatar;
    private InputMethodManager inputMethodManager;
    private String toAddUsername;
    ProgressDialog progressDialog;
    private Context mContext;
    ArrayList<HashMap<String, Object>> mList = new ArrayList<HashMap<String, Object>>();
    private ListView mLvSearchFriends;
    SearchFriendsAdapter mSearchFriendsAdapter;
    ProgressDialog pd;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContext = this;
        setContentView(R.layout.activity_add_contact_search);
        mTextView = (TextView) findViewById(R.id.add_list_friends);
        pd = new ProgressDialog(AddContactSearchActivity.this,
                ProgressDialog.THEME_HOLO_LIGHT);
        editText = (EditText) findViewById(R.id.edit_note);
        String strAdd = getResources().getString(R.string.add_friend);
        mTextView.setText(strAdd);
        nameText = (TextView) findViewById(R.id.name);
        searchBtn = (Button) findViewById(R.id.search);
        avatar = (ImageView) findViewById(R.id.avatar);
        inputMethodManager = (InputMethodManager) getSystemService(
                Context.INPUT_METHOD_SERVICE);
        mLvSearchFriends = (ListView) findViewById(R.id.lv_search_friends);
        mSearchFriendsAdapter = new SearchFriendsAdapter(mContext, mList);
        mLvSearchFriends.setAdapter(mSearchFriendsAdapter);
        mLvSearchFriends.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {
                Intent intent = new Intent();
                intent.setClass(mContext, PersonalDetailsActivity.class);
                intent.putExtra("username", mSearchFriendsAdapter
                        .getItem(position).get("Username").toString());
                intent.putExtra("type", "add");
                mContext.startActivity(intent);
            }
        });
        mSearchFriendsAdapter
                .setAdapterListener(new SearchFriendsAdapterListener() {

                    @Override
                    public void onItemClick(int position) {
                    }

                    @Override
                    public void addClick(int position) {
                        // Toast.makeText(mContext, "正在等待对方回应",
                        // Toast.LENGTH_LONG)
                        // .show();
                        // try {
                        // EMContactManager.getInstance().addContact(
                        // mSearchFriendsAdapter.getItem(position)
                        // .get("Username").toString(), "");
                        // } catch (EaseMobException e) {
                        //
                        // }
                        addContact(mSearchFriendsAdapter.getItem(position)
                                .get("Username").toString());
                    }
                });
    }

    /**
     * 查找contact
     * 
     * @param v
     */
    public void searchContact(View v) {
        final String name = editText.getText().toString();
        String saveText = searchBtn.getText().toString();
        if (getString(R.string.button_search).equals(saveText)) {
            toAddUsername = name;
            if (TextUtils.isEmpty(name)) {
                String st = getResources()
                        .getString(R.string.Please_enter_a_username);
                startActivity(new Intent(this, AlertDialog.class)
                        .putExtra("msg", st));
                return;
            }
            pd.setMessage(getString(R.string.search_now));
            pd.show();
            SearchFriendsJson searchFriendsJson = new SearchFriendsJson(
                    toAddUsername, Config.getUserToken());
            searchFriendRequest(Constants.SEARCHFRIENDS, searchFriendsJson);
            // TODO 从服务器获取此contact,如果不存在提示不存在此用户

        }
    }

    /**
     * 查询好友请求
     *
     * @param searchFriendsUrl
     * @param mSearchFriendsJson
     */
    private void searchFriendRequest(String searchFriendsUrl,
            SearchFriendsJson mSearchFriendsJson) {
        mList.clear();
        Log.i(TAG,
                "<searchFriendRequest>--<onResponse>--上传的JSon数据：  GetTokenJson = "
                        + mSearchFriendsJson);
        Type type = new TypeToken<BaseResult<List<UserVO>>>() {
        }.getType();
        JsonListRequest<BaseResult<List<UserVO>>> request = new JsonListRequest<BaseResult<List<UserVO>>>(
                mContext, Method.POST, searchFriendsUrl,
                mSearchFriendsJson.toString(), null, null, type, false,
                new Listener<BaseResult<List<UserVO>>>() {

                    @Override
                    public void onResponse(BaseResult<List<UserVO>> arg0) {
                        Log.i(TAG,
                                "<searchFriendRequest>--<onResponse>--服务器返回的JSon数据：  arg0 = "
                                        + arg0);
                        int code = 1;
                        String message = null;
                        List<UserVO> data = null;
                        message = arg0.getMessage();
                        code = arg0.getCode();
                        data = arg0.getData();
                        Log.i(TAG,
                                "<searchFriendRequest>--<onResponse>--服务器返回的JSon数据：  message = "
                                        + message);
                        Log.i(TAG,
                                "<searchFriendRequest>--<onResponse>--服务器返回的JSon数据：  code = "
                                        + code);
                        Log.i(TAG,
                                "<searchFriendRequest>--<onResponse>--服务器返回的JSon数据：  data = "
                                        + data);
                        if (code == 0) {
                            if (data.size() > 0) {
                                for (int i = 0; i < data.size(); i++) {
                                    HashMap<String, Object> map = new HashMap<String, Object>();
                                    map.put("Username",
                                            data.get(i).getUsername());
                                    map.put("Nickname",
                                            data.get(i).getNickname());
                                    if (data.get(i).getImagepath() != null) {
                                        map.put("Imagepath",
                                                data.get(i).getImagepath());
                                    } else {
                                        map.put("Imagepath", "");
                                    }
                                    map.put("Id", data.get(i).getId());
                                    map.put("Telphone",
                                            data.get(i).getTelphone());
                                    mList.add(map);
                                }

                            } else {
                                Toast.makeText(mContext, getString(R.string.user_not_exist),
                                        Toast.LENGTH_LONG).show();
                            }

                        } else {
                            Toast.makeText(mContext, getString(R.string.search_error),
                                    Toast.LENGTH_LONG).show();
                        }
                        mSearchFriendsAdapter.notifyDataSetChanged();
                        pd.dismiss();
                    }
                }, new ErrorListener() {

                    @Override
                    public void onErrorResponse(VolleyError arg0) {
                        NetworkResponse response = arg0.networkResponse;
                        if (response != null) {
                            try {
                                String json = new String(response.data,
                                        HttpHeaderParser.parseCharset(
                                                response.headers));
                                Log.i(TAG,
                                        "<searchFriendRequest>--<onErrorResponse> -- json = "
                                                + json);
                                Log.i(TAG,
                                        "<searchFriendRequest>--<onErrorResponse> -- response.data = "
                                                + response.data);
                                Log.i(TAG,
                                        "<searchFriendRequest>--<onErrorResponse> -- response.headers = "
                                                + response.headers);
                            } catch (UnsupportedEncodingException e) {
                                e.printStackTrace();
                            }
                        }
                        if (arg0 != null && arg0.toString().contains(
                                "com.android.volley.NoConnectionError")) {
                            Toast.makeText(mContext,
                                    getString(R.string.network_unavailable),
                                    Toast.LENGTH_SHORT).show();
                        } else if (arg0 != null && arg0.toString()
                                .contains("com.android.volley.ServerError")) {
                            Toast.makeText(mContext,
                                    getString(
                                            R.string.service_temporarily_unavailable),
                                    Toast.LENGTH_SHORT).show();
                        } else if (arg0 != null && arg0.toString()
                                .contains("com.android.volley.TimeoutError")) {
                            Toast.makeText(mContext,
                                    getString(R.string.time_out_error),
                                    Toast.LENGTH_SHORT).show();
                        } else {
                            Toast.makeText(mContext,
                                    getString(R.string.request_fail),
                                    Toast.LENGTH_SHORT).show();
                        }
                        Log.i(TAG,
                                "<searchFriendRequest>--<onErrorResponse>--服务器请求失败： arg0 = "
                                        + arg0);
                        Log.i(TAG,
                                "<searchFriendRequest>--<onErrorResponse>--服务器请求失败： response = "
                                        + response);
                        pd.dismiss();
                    }

                });
        VolleyUtil.addRequest(request);
    }

    public void back(View v) {
        finish();
    }

    /**
     * 添加contact
     * 
     * @param
     */
    public void addContact(final String name) {
        if (Config.getUserName().equals(name)) {
            String str = getString(R.string.not_add_myself);
            startActivity(
                    new Intent(this, AlertDialog.class).putExtra("msg", str));
            return;
        }

        if (((DemoHXSDKHelper) HXSDKHelper.getInstance()).getContactList()
                .containsKey(name)) {
            // 提示已在好友列表中，无需添加
            if (EMClient.getInstance().contactManager().getBlackListUsernames()
                    .contains(name)) {
                startActivity(new Intent(this, AlertDialog.class)
                        .putExtra("msg", getString(R.string.is_your_friend)));
                return;
            }
            String strin = getString(R.string.This_user_is_already_your_friend);
            startActivity(
                    new Intent(this, AlertDialog.class).putExtra("msg", strin));
            return;
        }

        progressDialog = new ProgressDialog(AddContactSearchActivity.this,
                ProgressDialog.THEME_HOLO_LIGHT);
        String stri = getResources().getString(R.string.Is_sending_a_request);
        progressDialog.setMessage(stri);
        progressDialog.setCanceledOnTouchOutside(false);
        progressDialog.show();

        new Thread(new Runnable() {
            public void run() {

                try {
                    // demo写死了个reason，实际应该让用户手动填入
                    String s = getResources().getString(R.string.Add_a_friend);
                    EMClient.getInstance().contactManager().addContact(name,
                                HXPreferenceUtils.getInstance()
                                        .getCurrentUserAvatar());
                    runOnUiThread(new Runnable() {
                        public void run() {
                            progressDialog.dismiss();
                            String s1 = getResources()
                                    .getString(R.string.send_successful);
                            Toast.makeText(getApplicationContext(), s1, 1)
                                    .show();
                        }
                    });
                } catch (final Exception e) {
                    runOnUiThread(new Runnable() {
                        public void run() {
                            progressDialog.dismiss();
                            String s2 = getResources().getString(
                                    R.string.Request_add_buddy_failure);
                            Toast.makeText(getApplicationContext(),
                                    s2 + e.getMessage(), 1).show();
                        }
                    });
                }
            }
        }).start();
    }
}
